﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Data.Helpers.FindSearchRichParser;

namespace CtyProject.UserControls
{
    //声明委托
    //public delegate void ShowTaskResultDelegate(string value); 
    //改为Action不需要在类外声明
    public partial class MultiThreadRefreshUc : DevExpress.XtraEditors.XtraUserControl
    {
        private bool uiSwitch = false;
        private CancellationTokenSource cts;
        private readonly Random random = new Random();
        //public ShowTaskResultDelegate showTaskResult;//定义委托变量
        //public Action<string> showTaskResult;
        public event Action<string> showTaskResult;
        public MultiThreadRefreshUc()
        {
            InitializeComponent();
            cts = new CancellationTokenSource();
        }

        public async void ChangeRefreshUi()
        {
            uiSwitch = !uiSwitch;//切换状态

            if (uiSwitch)
            {
                cts = new CancellationTokenSource();
                //启动线程刷新与任务刷新
                StartThreadRefresh(cts.Token);
                await StartTaskRefresh(cts.Token);
            }
            else
            {
                
                cts.Cancel();  //取消多线程和异步任务
                cts.Dispose(); // 确保释放旧的CancellationTokenSource资源
            }
        }

        private void StartThreadRefresh(CancellationToken token)
        {

            var thread = new Thread(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    try
                    {
                        UpdateUi(() =>
                        {
                            this.textEditThread.Text = random.Next(1, 100).ToString();
                        });
                        //Thread.Sleep(300);//在线程睡眠的过程中无法响应取消
                        token.WaitHandle.WaitOne(TimeSpan.FromMilliseconds(300));
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw;
                    }

                }
            });

            thread.Start();
        }

        private async Task StartTaskRefresh(CancellationToken token)
        {
            await Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    try
                    {
                        UpdateUi(() =>
                        {
                            
                            this.textEditTask.Text = random.Next(1, 100).ToString();
                            //使用委托通知主窗体更新数据
                            showTaskResult?.Invoke(this.textEditTask.Text);
                        });
                        //在延迟期间也支持取消
                        await Task.Delay(300, token);
                    }
                    catch (OperationCanceledException)
                    {
                        Console.WriteLine("异步任务取消成功");
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw;
                    }
                }
            }, token);

        }

        //跨线程更新UI
        private void UpdateUi(Action action)
        {
            //判断窗体是否被创建
            if (this.IsHandleCreated)
            {
                this.Invoke(action);
            }
        }
    }
}
